// import Vue from 'vue';
import Qs from 'qs';
import axios from 'axios';
// import { Confirm, Alert, Toast, Notify, Loading } from 'vue-ydui/dist/lib.rem/dialog';
import Querystring from 'query-string';
import storage from './store/storage.js';
// const baseURL = 'http://192.168.3.136:9096';
// const baseURL = 'http://120.78.201.213:9096';
// const baseURL = 'http://192.168.2.210:9096';
// const baseURL = 'http://192.168.2.12:9096';
// const baseURL = 'http://127.0.0.1:9096';
const baseURL = 'http://estate.siyueluo.com';
// Vue.prototype.$dialog = {
//   confirm: Confirm,
//   alert: Alert,
//   toast: Toast,
//   notify: Notify,
//   loading: Loading,
// };


axios.defaults.timeout = 10000;

// 如果当前已经登录就添加登录信息
axios.interceptors.request.use(config => {
  const token = storage.get("token")
  // console.log(token)
  if (token && token !== 'undefined') {
    config.headers['x-access-token'] = token;
  }

  return config;
});
// 如果当前未登录，就清空登录信息
axios.interceptors.response.use(response => {

  if (response.data.code === 50003 || response.data.code === 50009) {

    // 50003  未授权
    // 50009 未登录
    //  微信授权
    // console.log("授权")
    // let appId = 'wxe2f71ea9af8ea232';
    let appId = storage.get("appId", 'local');
    if (!appId) {
      return response;
    }
    const query = Querystring.parse(location.search)
    let snsApi = query.snsApi ? query.snsApi : "userinfo"
    const url = baseURL + "/oauth2/authorize?appId=" + appId + "&snsApi=" + snsApi + "&from=" + encodeURIComponent(location.href);
    console.log(url)
    window.location.href = url
  }
  if (response.data.code === 50008) {
    //  登录过期
    window.location.href = "/login"

  }

  return response;
});

function error(message) {
  if (message) {
    console.log(message);
    // this.$dialog.toast({mes: message, timeout: 1000});
  } else {
    console.log("加载失败")
    // this.$dialog.toast({mes: '加载失败', timeout: 1000});
  }

}


export default {
  baseURL: baseURL,
  img: function (url) {
    return baseURL + url;
  },
  req: function (url, params) {
    return new Promise((resolve, reject) => {
      axios({
        url: url,
        method: 'GET',
        params: params,
        withCredentials: true
      }).then(response => {
        resolve(response.data);
      }).catch(err => {
        reject(err);
      });
    });
  },
  get: function (url, params) {
    return new Promise((resolve, reject) => {
      axios({
        url: url,
        method: 'GET',
        params: params,
        baseURL: baseURL,
        withCredentials: true
      }).then(response => {
        const result = response.status;
        if (result == '200') {
          if (response.data && response.data.code && (response.data.code === 50003 || response.data.code === 50008 || response.data.code === 50009)) {
            reject(response)
          }
          resolve(response);
        } else {
          // if (response.)
          error(response.message);
          reject(response);
        }
      }).catch(err => {
        reject(err);
      });
    });
  },
  post: function (url, data) {
    return new Promise((resolve, reject) => {
      axios({
        url: url,
        data: data,
        method: 'POST',
        baseURL: baseURL,
        withCredentials: true,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        transformRequest: function (data) {
          return Qs.stringify(data, {
            arrayFormat: 'repeat'
          });
        }
      }).then(response => {
        const result = response.status;
        if (result == '200') {
          if (response.data.code === 50003) {
            reject(response);
          } else if (response.data.code === 50008) {
            reject(response);
          } else if (response.data.code === 50009) {
            reject(response);
          }
          resolve(response);
        } else {
          error(response.message);
          reject(response);
        }
      }).catch(err => {
        reject(err);
      });
    });
  },
  postHead:function(url, data) {
    return new Promise((resolve, reject) => {
      axios({
        url: url,
        data: data,
        method: 'POST',
        baseURL: baseURL,
        withCredentials: true,
      }).then(response => {
        const result = response.status;
        if (result == '200') {
          if (response.data.code === 50003) {
            reject(response);
          } else if (response.data.code === 50008) {
            reject(response);
          } else if (response.data.code === 50009) {
            reject(response);
          }
          resolve(response);
        } else {
          error(response.message);
          reject(response);
        }
      }).catch(err => {
        reject(err);
      });
    });
  },

  postFile: function (url, data) {
    return new Promise((resolve, reject) => {
      axios({
        url: url,
        data: data,
        method: 'POST',
        baseURL: baseURL,
        withCredentials: true,
        headers: {
          'Content-Type': 'multipart/form-data',
          'x-access-token': storage.get("token")
        },
      }).then(response => {
        const result = response.status;
        if (result == '200') {
          resolve(response);
        } else {
          error(response.message);
          reject(response);
        }
      }).catch(err => {
        reject(err);
      });
    });
  },
  json: function (url, data) {
    return new Promise((resolve, reject) => {
      axios({
        url: url,
        data: data,
        method: 'POST',
        baseURL: baseURL,
        withCredentials: true
      }).then(response => {
        const result = response.status;
        if (result == '200') {
          resolve(response);
        } else {
          error(response.message);
          reject(response);
        }
      }).catch(err => {
        reject(err);
      });
    });
  },
  cache: function (url, validate) {
    return new Promise((resolve, reject) => {
      const result = storage.getObj(url); // 加载缓存的数据

      // 缓存必须存在 & 缓存有效性效验
      if (result && (typeof (validate) != 'function' || validate(result))) {
        return resolve(result);
      }

      // 通过网络加载数据
      axios({
        url: url,
        method: 'GET',
        baseURL: baseURL,
        withCredentials: true
      }).then(response => {
        storage.put(url, response.data);
        resolve.call(response, response.data);
      }).catch(err => {
        reject(err);
      });
    });
  }
}
